package adger.me.yili.utils;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

/**
 * Created by heyue on 16/1/28.
 */
public class DB {
    public static DbManager.DaoConfig daoConfig = new DbManager.DaoConfig()
            .setDbName("yuli.db")
            // 不设置dbDir时, 默认存储在app的私有目录.
//            .setDbDir(new File(Environment.getExternalStorageDirectory().getAbsolutePath())) // "sdcard"的写法并非最佳实践, 这里为了简单, 先这样写了.
            .setDbVersion(2)
            .setDbOpenListener(new DbManager.DbOpenListener() {
                @Override
                public void onDbOpened(DbManager db) {
                    // 开启WAL, 对写入加速提升巨大
                    db.getDatabase().enableWriteAheadLogging();
                }
            })
            .setDbUpgradeListener(new DbManager.DbUpgradeListener() {
                @Override
                public void onUpgrade(DbManager db, int oldVersion, int newVersion) {
                    // TODO: ...
                    // db.addColumn(...);
                    // db.dropTable(...);
                    // ...
                    // or
                    try {
                        db.dropDb();
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                }
            });
    private static DbManager xdbManager;
    private static DB mInstance;


    public static DbManager getXInstance()
    {
        if (xdbManager == null)
        {
            synchronized (DB.class)
            {
                if (xdbManager == null)
                {
                    xdbManager = x.getDb(daoConfig);
                }
            }
        }
        return xdbManager;
    }
    public static DB getInstance()
    {
        if (mInstance == null)
        {
            synchronized (DB.class)
            {
                if (mInstance == null)
                {
                    mInstance = new DB();
                }
            }
        }
        return mInstance;
    }

    public  <T> void saveOrUpdate(T t) {
        mInstance.getXInstance();
        try {
            //创建表
            xdbManager.saveOrUpdate(t);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }
    public  <T> T find(Class<T> cls) {
        mInstance.getXInstance();
        try {
           return  xdbManager.selector(cls).findFirst();
        } catch (DbException e) {
            e.printStackTrace();
        }
        return null;
    }


}
